package com.asap.demo.ck.handle;



import com.asap.demo.ck.table.JsonField;
import com.asap.demo.ck.table.JsonTable;
import com.asap.demo.ck.util.JsonParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


public class RuleParse  implements Serializable {
	private static final Logger logger = LoggerFactory.getLogger(RuleParse.class);

	private JsonTable tableDefine = null;
	private String tableInsertSql="";
	private String tableQuerySql="";
	private Map<String, String> configMap = null;
	public String getTableInsertSql() {return  tableInsertSql;}

	public String getTableQuerySql() {return  tableQuerySql;}

	public JsonTable getTableDefine() {
		return tableDefine;
	}


	public void setConfigMap(Map<String, String> configMap) {
		this.configMap = configMap;
	}

	public void parseData(String fileName){
		parseRule(readRule( fileName));
		formatSql();
	}


	public static String readRule(String fileName)
	{
		String data = null;
		FileInputStream fileInputStream =null;
		try{
			fileInputStream = new FileInputStream(new File(fileName));

			int readByte = 0;
			byte[] bytedata = new byte[204800];
			while(-1 != (readByte = fileInputStream.read(bytedata))){
			}

			data = new String(bytedata);
		}catch(IOException e){
			logger.error("read file error",e);
		}finally {
			if(fileInputStream!=null) {
				try {
					fileInputStream.close();
				} catch (IOException e) {
					logger.error("fileInputStream.close() ",e);
				}
			}
		}

		return data;
	}
	
	public void parseRule(String rule){
		Map<String, Object> mapInputRule= JsonParser.<String, Object>parseFrom(rule.trim());
		tableDefine = new JsonTable();
		tableDefine.setTableName((String)mapInputRule.get("table_name"));
		tableDefine.setTopicPrimaryKey((String)mapInputRule.get("topic_primary_key"));
		tableDefine.setPrimaryKey((String)mapInputRule.get("primary_key"));
		List fieldRules=(List<Object>)mapInputRule.get("fields");
		List<JsonField> listFields = new ArrayList<JsonField>();
		for(int i=0; i<fieldRules.size(); i++){
			Map<Object, Object> fieldJson = (Map<Object, Object>)fieldRules.get(i);
			JsonField field = new JsonField();
			field.setDbFieldName((String)fieldJson.get("db_field_name"));
			field.setTopicFieldName((String)fieldJson.get("topic_field_name"));
			field.setFieldType((String)fieldJson.get("field_type"));
			field.setDefaultValue((String)fieldJson.get("default_value"));
			listFields.add(field);
		}
		tableDefine.setJsonFieldList(listFields);
	}


	public void formatSql() {
		// 遍历自定义配置中的所有表
		StringBuffer insertSql = new StringBuffer();
		StringBuffer deleteSql = new StringBuffer();

		insertSql.append("insert into ");
		insertSql.append(tableDefine.getTableName());
		insertSql.append(" (");
		List<JsonField> fields = tableDefine.getJsonFieldList();
		int length = fields.size();
		for (int i = 0; i < length; i++) {
			if(fields.get(i).getFieldType().contains("Nested")){
				insertSql.append("`").append(fields.get(i).getDbFieldName()).append(".KEY`").append(",");
				insertSql.append("`").append(fields.get(i).getDbFieldName()).append(".VAL`");
			}else {
				insertSql.append("`").append(fields.get(i).getDbFieldName()).append("`");
			}
			if (i < length - 1) {
				insertSql.append(",");
			}
		}

		insertSql.append(") values(");
		for (int i = 0; i < length; i++) {
			if(fields.get(i).getFieldType().contains("Nested")) {
				insertSql.append("?,?");
			}else {
				insertSql.append("?");
			}
			if (i < length - 1) {
				insertSql.append(",");
			}
		}

		insertSql.append(") ");
		tableInsertSql = insertSql.toString();

		tableQuerySql = "SELECT COUNT(*) as TOTAL_NUM FROM " + tableDefine.getTableName()+" where " + tableDefine.getPrimaryKey() + "=?";
	}
}
